﻿using AutoMapper;
using B.S.RbacData.Domain;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using B.S.RbacData.Read.API.Applications.Commands.RBAC;
using B.S.RbacData.Read.API.Dtos;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.RbacData.Read.API.Applications.CommandHandlters.RBAC
{
    /// <summary>
    /// 角色权限信息的处理
    /// </summary>
    public class GetRolePermissionCommandHandlter : IRequestHandler<GetRolePermissionCommand, ApiPaging<RolePermissionDtos>>
    {
        private readonly IBaseRepository<RoleModel> roleRep;
        private readonly IBaseRepository<RolePermissionModel> rolepermissionRep;
        private readonly IBaseRepository<PermissionModel> permissionRep;
        private readonly IMapper mapper;

        public GetRolePermissionCommandHandlter(IBaseRepository<RoleModel> RoleRep, IBaseRepository<RolePermissionModel> rolepermissionRep, IBaseRepository<PermissionModel> permissionRep, IMapper mapper)
        {
            roleRep = RoleRep;
            this.rolepermissionRep = rolepermissionRep;
            this.permissionRep = permissionRep;
            this.mapper = mapper;
        }


        public async Task<ApiPaging<RolePermissionDtos>> Handle(GetRolePermissionCommand request, CancellationToken cancellationToken)
        {

            #region 错误写法
            //var list = roleRep.GetAll().AsNoTracking();


            //List<RolePermissionDtos> dtos = new List<RolePermissionDtos>();


            //foreach (var item in list.ToList())
            //{

            //    var rolepermissions = rolepermissionRep.GetAll().Where(x => x.RoleId == item.ID).ToList();


            //    foreach (var items in rolepermissions)
            //    {
            //        var permission = permissionRep.GetAll().Where(x => x.ID == items.PermissionId).Select(x => x.PermissionName).ToList();

            //        dtos.Add(new RolePermissionDtos()
            //        {
            //            CreateTime = DateTime.Now,
            //            IsDeleted = item.IsDeleted,
            //            ID = items.RoleId,
            //            IsState = item.IsState,
            //            Permissions =string.Join(",", permission),
            //            RoleName = item.RoleName,
            //            XuHao = item.XuHao,
            //        });

            //    }

            //}

            //if (!string.IsNullOrEmpty(request.RoleName))
            //{

            //    list = list.Where(x => x.RoleName.Contains(request.RoleName));

            //}

            //var totalcount = list.Count();
            //var totalpage = (int)Math.Ceiling(1.0 * totalcount / request.PageSize);


            //list = list.OrderBy(x => x.ID).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            //return new ApiPaging<RolePermissionDtos>()
            //{
            //    code = ResultEnumCode.Ok,
            //    message = "获取成功",
            //    PageCount = totalpage,
            //    TotalCount = totalcount,
            //    PageData = mapper.Map<List<RolePermissionDtos>>(list.ToList())

            //};
            #endregion 

            // 构建基础查询，获取未删除的角色记录
            // 如果传入了角色名称，则按角色名称模糊查询
            var query = roleRep.GetAll()
       .AsNoTracking()
       .Where(x => (string.IsNullOrEmpty(request.RoleName) || x.RoleName.Contains(request.RoleName))&&x.IsDeleted==false);

            // 计算总记录数和总页数
            var totalCount = await query.CountAsync(cancellationToken);
            var totalPages = (int)Math.Ceiling(1.0 * totalCount / request.PageSize);

            // 执行分页查询，获取角色列表
            // 按ID排序并应用分页参数
            var roles = await query
                .OrderBy(x => x.ID)
                .Skip((request.PageIndex - 1) * request.PageSize)
                .Take(request.PageSize)
                .Select(r => new RolePermissionDtos
                {
                    ID = r.ID,
                    RoleName = r.RoleName,
                    IsDeleted = r.IsDeleted,
                    IsState = r.IsState,
                    XuHao = r.XuHao,
                    CreateTime =r.CreateTime,
                    // 获取角色对应的权限名称列表
                    // 通过角色-权限关联表和权限表连接查询
                    // 将权限名称用逗号拼接成字符串
                    Permissions = string.Join(",",
                        rolepermissionRep.GetAll()
                            .Where(rp => rp.RoleId == r.ID)
                            .Join(permissionRep.GetAll().Where(x=>!x.IsDeleted),
                                rp => rp.PermissionId,
                                p => p.ID,
                                (rp, p) => p.PermissionName)
                    )
                })
                .ToListAsync(cancellationToken);

            return new ApiPaging<RolePermissionDtos>
            {
                code = ResultEnumCode.Ok,
                message = "获取成功",
                PageCount = totalPages,
                TotalCount = totalCount,
                PageData = roles
            };



        }

    }
}
